'use strict';

const Controller = require('../base_controller');
const uuidv4 = require('uuid/v4');


class RecordController extends Controller {
  // 增加一条数据
  async addRecord() {
    const { ctx } = this;
    // 解构
    const {
      type,
      name,
      desc,
      truth,
      publish_time,
      publish_url,
      publish_name,
      publish_desc,
      licence,
      licence_seat,
      licence_time,
      departure,
      arrive,
      carrier_desc,
      province,
      cities,
      area,
      address,
    } = ctx.request.body;

    // 校验
    const parameterRule = {
      type: { type: 'enum', required: true, values: [ 'train', 'plane', 'ship', 'bus', 'taxi', 'community', 'other' ] },
      name: 'string?',
      desc: 'string?',
      truth: 'boolean?',
      publish_time: 'dateTime?',
      publish_url: 'string?',
      publish_name: 'string?',
      publish_desc: 'string?',
      licence: 'string?',
      licence_seat: 'string?',
      licence_time: 'dateTime?',
      departure: 'string?',
      arrive: 'string?',
      carrier_desc: 'string?',
      province: 'string?',
      cities: 'string?',
      area: 'string?',
      address: 'string?',
    };

    try {
      ctx.validate(parameterRule);
    } catch (err) {
      ctx.logger.warn(err.errors);
      this.httpError400({ data: err.errors, msg: '参数不符合规范', code: 400000 });
      return;
    }

    const uuid = uuidv4().toUpperCase();

    // 插入数据库
    const param = {
      uuid,
      type,
      name,
      desc,
      truth,
      publish_time,
      publish_url,
      publish_name,
      publish_desc,
      licence,
      licence_seat,
      licence_time,
      departure,
      arrive,
      carrier_desc,
      province,
      cities,
      area,
      address,
    };


    const result = await ctx.model.Record.create(param)
      .then(data => {
        return { success: true, data };
      }).catch(e => {
        return { success: false, data: e };
      });
    if (!result.success) {
      this.httpError500({ data: null });
      return;
    }

    this.success({ data: result.data });
  }

  // 根据uid检索一条数据
  async findRecordOne() {
    const { ctx } = this;
    // 解构
    const {
      id,
    } = ctx.params;

    // 校验
    const parameterRule = {
      id: 'string',
    };

    try {
      ctx.validate(parameterRule, ctx.params);
    } catch (err) {
      ctx.logger.warn(err.errors);
      this.httpError400({ data: err.errors, msg: '参数不符合规范', code: 400000 });
      return;
    }

    const result = await ctx.model.Record.findOne({
      where: {
        uuid: id,
      } })
      .then(data => {
        return { success: true, data };
      }).catch(e => {
        return { success: false, e };
      });
    if (!result.success) {
      this.httpError500({ data: null });
      return;
    }

    if (result.data === null) {
      this.httpError404({ data: null });
      return;
    }

    this.success({ data: result.data });
  }

  // 按照条件检索数据
  async findRecordList() {
    const { ctx } = this;
    // 解构
    const {
      page = '1',
      per_page = '10',
      sortby = 'updated_at',
      order = 'desc',
      type,
      licence,
      licence_time,
      province,
      cities,
      area,
    } = ctx.request.query;

    // 校验
    const parameterRule = {
      page: 'string',
      per_page: 'string',
      sortby: { type: 'enum', required: true, values: [ 'updated_at', 'publish_time', 'licence_time', 'created_at' ] },
      order: { type: 'enum', required: true, values: [ 'desc', 'asc' ] },
      type: { type: 'enum', required: false, values: [ 'train', 'plane', 'ship', 'bus', 'taxi', 'community', 'other' ] },
      licence: 'string?',
      licence_time: 'dateTime?',
      province: 'string?',
      cities: 'string?',
      area: 'string?',
    };

    try {
      ctx.validate(parameterRule, {
        page,
        per_page,
        sortby,
        order,
        type,
        licence,
        licence_time,
        province,
        cities,
        area,
      });
    } catch (err) {
      ctx.logger.warn(err.errors);
      this.httpError400({ data: err.errors, msg: '参数不符合规范', code: 400000 });
      return;
    }

    let result = { success: false, data: null };

    // 如果type不存在
    if (!type) {
      result = await this.ctx.service.record.record.findDefault({
        page,
        per_page,
        sortby,
        order,
      });
    }

    // 如果类型为火车，飞机，轮船，大巴，则进行普通的查询
    if (type === 'train' || type === 'plane' || type === 'ship' || type === 'bus' || type === 'taxi') {
      result = await this.ctx.service.record.record.findDefaultTransport({
        page,
        per_page,
        sortby,
        order,
        type,
        licence,
        licence_time,
      });
    }

    // 其他类型的查询检索操作还未完成
    if (type === 'community') {
      result = await this.ctx.service.record.record.findDefaultCommunity({
        page,
        per_page,
        sortby,
        order,
        type,
        province,
        cities,
        area,
      });
    }

    this.success({ data: result.data });
  }

  // 根据uid修改一条数据
  async updateRecordOne() {
    const { ctx } = this;

    // 解构
    const {
      id,
    } = ctx.params;

    // 校验
    const parameterRule = {
      id: 'string',
    };

    try {
      ctx.validate(parameterRule, ctx.params);
    } catch (err) {
      ctx.logger.warn(err.errors);
      this.httpError400({ data: err.errors, msg: '参数不符合规范', code: 400000 });
      return;
    }

    if (Object.keys(ctx.request.body).length === 0) {
      this.httpError400({ data: null, msg: '修改的参数不能为空', code: 400000 });
      return;
    }

    // 解构
    const {
      type,
      status,
      name,
      desc,
      truth,
      is_show,
      publish_time,
      publish_url,
      publish_name,
      publish_desc,
      licence,
      licence_seat,
      licence_time,
      departure,
      arrive,
      carrier_desc,
      province,
      cities,
      area,
      address,
    } = ctx.request.body;

    // 校验
    const bodyRule = {
      type: { type: 'enum', required: false, values: [ 'train', 'plane', 'ship', 'bus', 'taxi', 'community', 'other' ] },
      status: { type: 'enum', required: false, values: [ 0, 1, 3 ] }, // 默认为0为未审核，1为审核通过等待上链，2位审核通过并且已经上链，3为已驳回
      name: 'string?',
      desc: 'string?',
      truth: 'boolean?',
      is_show: 'boolean?',
      publish_time: 'dateTime?',
      publish_url: 'string?',
      publish_name: 'string?',
      publish_desc: 'string?',
      licence: 'string?',
      licence_seat: 'string?',
      licence_time: 'dateTime?',
      departure: 'string?',
      arrive: 'string?',
      carrier_desc: 'string?',
      province: 'string?',
      cities: 'string?',
      area: 'string?',
      address: 'string?',
    };

    const updateData = {
      type,
      status,
      name,
      desc,
      truth,
      is_show,
      publish_time,
      publish_url,
      publish_name,
      publish_desc,
      licence,
      licence_seat,
      licence_time,
      departure,
      arrive,
      carrier_desc,
      province,
      cities,
      area,
      address,
    };

    try {
      ctx.validate(bodyRule, updateData);
    } catch (err) {
      ctx.logger.warn(err.errors);
      this.httpError400({ data: err.errors, msg: '参数不符合规范', code: 400000 });
      return;
    }

    const findResult = await ctx.model.Record.findOne({
      where: {
        uuid: id,
      } })
      .then(data => {
        return { success: true, data };
      }).catch(e => {
        return { success: false, e };
      });
    if (!findResult.success) {
      this.httpError500({ data: findResult.data });
      return;
    }

    if (findResult.data === null) {
      this.httpError404({ data: null, msg: '未找到此id对应的数据' });
      return;
    }

    const updateResult = await ctx.model.Record.update(updateData, {
      where: {
        uuid: id,
      } })
      .then(data => {
        return { success: true, data };
      }).catch(e => {
        return { success: false, e };
      });
    if (!updateResult.success) {
      this.httpError500({ data: updateResult.data });
      return;
    }

    const findResultLast = await ctx.model.Record.findOne({
      where: {
        uuid: id,
      } })
      .then(data => {
        return { success: true, data };
      }).catch(e => {
        return { success: false, e };
      });
    if (!findResultLast.success) {
      this.httpError500({ data: findResultLast.data });
      return;
    }

    this.success({ data: findResultLast.data });
  }

  // 根据uid删除一条数据
  async deleteRecordOne() {
    const { ctx } = this;
    // 解构
    const {
      id,
    } = ctx.params;

    // 校验
    const parameterRule = {
      id: 'string',
    };

    try {
      ctx.validate(parameterRule, ctx.params);
    } catch (err) {
      ctx.logger.warn(err.errors);
      this.httpError400({ data: err.errors, msg: '参数不符合规范', code: 400000 });
      return;
    }

    const findResult = await ctx.model.Record.findOne({
      where: {
        uuid: id,
      } })
      .then(data => {
        return { success: true, data };
      }).catch(e => {
        return { success: false, e };
      });
    if (!findResult.success) {
      this.httpError500({ data: findResult.data });
      return;
    }

    if (findResult.data === null) {
      this.success({ data: null });
      return;
    }

    const updateResult = await ctx.model.Record.update({ valid: 0 }, {
      where: {
        uuid: id,
      } })
      .then(data => {
        return { success: true, data };
      }).catch(e => {
        return { success: false, e };
      });
    if (!updateResult.success) {
      this.httpError500({ data: updateResult.data });
      return;
    }

    this.success({ data: null });
  }

}

module.exports = RecordController;
